<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="40%" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import {ref, computed, unref,useAttrs} from 'vue';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {configFormSchema} from './config.data';
  import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import { saveOrUpdate , getConfig } from './config.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  const { createMessage } = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const rowId = ref('');
  const record = ref<any>({})
  // 自适应列配置
  const adaptiveColProps: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 24, // ≥992px
    xl: 24, // ≥1200px
    xxl: 24, // ≥1600px
  }
  //表单配置
  const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 80,
    schemas: configFormSchema,
    showActionButtonGroup: false,
    wrapperCol: adaptiveColProps,
  });
  
  //表单赋值
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    console.log('record', data.record);
    
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter, loading: true})
    try {
      isUpdate.value = !!data?.isUpdate;
      if (unref(isUpdate)) {
        record.value = await getConfig({id: data.record.id})
        rowId.value = data.record.id;
      }
      
      setFieldsValue({ ...record.value })
      // 隐藏底部时禁用整个表单
      setProps({ disabled: !showFooter })
    } finally {
      setDrawerProps({ loading: false})
    }
  });
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增参数定义' : '编辑参数定义'));

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      console.log("submit: ", values);
      await saveOrUpdate({...values}, unref(isUpdate));
      
      //关闭弹窗
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      //刷新列表
      emit('success', {isUpdate: unref(isUpdate), values: {...values, id: rowId.value}});
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
